﻿local group_cfg = {
    {desc = "main", to = 89999, from = 1},
    {desc = "activity", to = 899999, from = 90000},
    {desc = "testing", to = 99999999, from = 899999}
}

local FileSystem = require("service.FileSystem")

LocalService = {}
function LocalService:Init( ... )
    FileSystem:prepareFolder(".database/service")
    FileSystem:prepareFolder(".database/levels/main")
    FileSystem:prepareFolder(".database/levels/activity")
    FileSystem:prepareFolder(".database/levels/testing")
    FileSystem:prepareFolder(".database/levels/error")
end

function LocalService.LevelUrl(levelId)
    local levelId = tonumber(levelId)
    for k,v in pairs(group_cfg) do
        if levelId >= v.from and levelId <= v.to then
            return string.format(".database/levels/%s/%d.json", v.desc, levelId)
        end
    end
    return string.format(".database/levels/%s/%d.json", "error", levelId)
end

function LocalService.SaveFile(fileName, content)
    local file = io.open(fileName, "w")
    if not file then
        return print("OPen file failed:" ..fileName)
    end

    if type(content) ~= "string" then
        content = table.tostring(content)
    end
    file:write(content)
    file:close()
end

function LocalService.OnService(serviceName, data)
    if type(data) ~= "string" then
        data = gJson.encode(data)
    end
    local fileName = serviceName ..".json"

    -- 某个关卡的信息
    if serviceName == "detail" then
        local inst = gJson.decode(data)
        local LevelSchema = require("service.TemplateEngine.LevelSchema")
        data = LevelSchema.Render(inst.gameData, gJson)
        fileName = string.format("../levels/%s.json", inst.levelId)
    elseif serviceName == "update" then -- 保存关卡
        local LevelSchema = require("service.TemplateEngine.LevelSchema")
        local inst = gJson.decode(data)
        inst.gameData = gJson.decode(inst.gameData)
        data = LevelSchema.Render(inst.gameData, gJson)
        fileName = string.format("../saved.%s.json", inst.id)
    elseif serviceName == "get" then
        local GetSchema = require("service.TemplateEngine.GetSchema")
        local inst = gJson.decode(data)
        data = GetSchema.Render(inst, gJson)
    end
    LocalService.SaveFile(".database/service/" ..fileName, data)
end

function LocalService.OnSyncWithServer()
    local co = nil
    local request = function(protocalName, objects, otherProtocalData)
        local params = ""
        objects = objects or {}
    
        objects['userName'] = "zhukai"
        for key, var in pairs(objects) do
            params = params.."&" .. key .. "="..var
        end

        local xhr = cc.XMLHttpRequest:new()
        -- 如果用户名为空，则说明没有登录信息，故意使请求报错
        local auth = mime.b64(gContext:getUser()..":"..gContext:getPassword())
        if (gContext:getUser() ~= "") then 
            xhr:setRequestHeader("Authorization", getAuthHeader())
        end 
       
        local host = "http://59.110.154.168:8084/BI/api/map.new.action?d=" .. protocalName
        xhr:open("POST", host)
  
        local function onReadyStateChange()
            if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
                local inst = gJson.decode(xhr.response)

                local data = require("service.TemplateEngine.LevelSchema").Render(inst.gameData, gJson) or "{}"
                local fileName = LocalService.LevelUrl(inst.levelId or 0)

                LocalService.SaveFile(fileName, data)
                LocalService.SaveFile(fileName ..".txt", inst.gameData)
            else
                print("Http ERROR Status Code:" .. xhr.status, xhr.responseCode)
            end
            coroutine.resume(co)
        end
        xhr:registerScriptHandler(onReadyStateChange)
        xhr:send("method="..protocalName..params)   
    end

    co = coroutine.create(function( ... )
        gContext.root.loadingLayer:setVisible(true)

        local fileName = ".database/service/get.json"
        local file = io.open(fileName, "r")
        local content = file:read("*a")
        file:close()

        local inst = gJson.decode(content)
        local counter = 0
        local total = #inst.levels
        for k,v in pairs(inst.levels) do
            counter = counter + 1
            print(string.format("[%s] processing level:%s %s %s", counter/total, k, v.levelId, v.desc))
            request("detail", {id = v.id})
            coroutine.yield()
        end
        gContext.root.loadingLayer:setVisible(false)
    end)
    coroutine.resume(co)
    print("All thing finished!")
end

LocalService:Init()

return LocalService